package com.sunfeng.n8;


import lombok.extern.slf4j.Slf4j;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 测试自定义线程池
 *
 * @author sunfeng
 * @date 2021/04/19 11:43
 **/

@Slf4j(topic = "c.TestPool")
public class TestPool {
    public static void main(String[] args) {
        ThreadPool threadPool = new ThreadPool(1, 1000, TimeUnit.MILLISECONDS, 1, (queue, task) -> {
            // 1、死等
            //   queue.put(task);
            // 2、超时等待
            // queue.offer(task,500,TimeUnit.MILLISECONDS);
            // 3、让调用这放弃任务执行
            // log.debug("放弃{}", task);
            // 4、让调用者抛出异常
            //  throw new RuntimeException("任务执行失败"+task);
            // 5、让调用者自己执行
            task.run();

        });
        for (int i = 0; i < 3; i++) {
            int j = i;
            threadPool.execute(() -> {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.debug("{}", j);
            });
        }
    }
}

@FunctionalInterface
interface RejectPolicy<T> {
    /**
     * 拒绝策略
     *
     * @param blockingQueue
     * @param task
     */
    void reject(BlockingQueue<T> blockingQueue, T task);
}


@Slf4j(topic = "c.ThreadPool")
class ThreadPool {

    /**
     * 阻塞队列
     */
    private BlockingQueue<Runnable> taskQueue;

    /**
     * 线程集合
     */
    private HashSet<Worker> workers = new HashSet<>();

    /**
     * 核心线程数
     */
    private int coreSize;
    /**
     * 获取任务时的超时时间
     */
    private long timeout;

    /**
     * 获取任务时间的超时单位
     */
    private TimeUnit timeUnit;

    private RejectPolicy<Runnable> rejectPolicy;

    /**
     * 执行任务
     *
     * @param task
     */
    public void execute(Runnable task) {
        // 当任务数没有超过coreSize()时，直接交给worker对象执行

        synchronized (workers) {
            if (workers.size() < coreSize) {
                Worker worker = new Worker(task);
                log.debug("新增 worker{},{}", worker, task);
                workers.add(worker);
                worker.start();
                // 如果任务数超过了coreSize()时，加入任务队列暂存
            } else {
                //taskQueue.put(task);
                // 1、死等
                // 2、超时等待
                // 3、让调用这放弃任务执行
                // 4、让调用者抛出异常
                // 5、让调用者自己执行
                // taskQueue.offer(task,timeout,timeUnit);
                taskQueue.tryPut(rejectPolicy, task);
            }
        }
    }


    public ThreadPool(int coreSize, long timeout, TimeUnit timeUnit, int queueCapcity, RejectPolicy<Runnable> rejectPolicy) {
        this.coreSize = coreSize;
        this.timeout = timeout;
        this.timeUnit = timeUnit;
        this.taskQueue = new BlockingQueue<>(queueCapcity);
        this.rejectPolicy = rejectPolicy;

    }

    class Worker extends Thread {
        private Runnable task;

        public Worker(Runnable task) {
            this.task = task;
        }

        @Override
        public void run() {
            //执行任务
            //1、当task不为空，执行任务
            //2、当task执行完毕，接着从任务队列获取任务并执行
            // while (task != null ||(task= taskQueue.take()) != null) {
            while (task != null || (task = taskQueue.poll(timeout, timeUnit)) != null) {
                try {
                    log.debug("正在执行...{}", task);
                    task.run();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    task = null;
                }
            }
            synchronized (workers) {
                log.debug("worker 被移除{}", this);
                // 从工作队列移除
                workers.remove(this);
            }
        }
    }
}

/**
 * 阻塞队列
 *
 * @param <T>
 */
@Slf4j(topic = "c.BlockingQueue")
class BlockingQueue<T> {

    /**
     * 1. 任务队列
     */
    private Deque<T> queue = new ArrayDeque<>();

    /**
     * 2. 锁
     */
    private ReentrantLock lock = new ReentrantLock();

    /**
     * 3. 生产者条件变量
     */
    private Condition fullWaitSet = lock.newCondition();

    /**
     * 4. 消费者条件变量
     */
    private Condition emptyWaitSet = lock.newCondition();

    /**
     * 容量
     */
    private int capcity;

    public BlockingQueue(int queueCapcity) {
        this.capcity = queueCapcity;
    }

    /**
     * 阻塞添加
     *
     * @param element
     */
    public void put(T element) {
        lock.lock();
        try {
            while (queue.size() == capcity) {
                try {
                    log.debug("等待 加入任务队列{}", element);
                    // 添加的时候队列是满的  则满的进行等待
                    fullWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            log.debug("加入任务队列{}", element);
            queue.addLast(element);
            // 添加成功之后唤醒 条件为空的等待
            emptyWaitSet.signal();
        } finally {
            lock.unlock();
        }
    }


    /***
     * 阻塞获取
     * @return
     */
    public T take() {
        lock.lock();

        try {
            while (queue.isEmpty()) {
                try {
                    emptyWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            T t = queue.removeFirst();
            fullWaitSet.signal();
            return t;

        } finally {
            lock.unlock();
        }
    }


    /**
     * 待超时时间的添加
     *
     * @param element
     * @param timeout
     * @param timeUnit
     * @return
     */
    public boolean offer(T element, long timeout, TimeUnit timeUnit) {
        lock.lock();
        try {
            long nanos = timeUnit.toNanos(timeout);

            while (queue.size() == capcity) {
                try {
                    if (nanos <= 0) {
                        return false;
                    }
                    log.debug("等待加入任务队列{}..", element);
                    // 添加的时候队列是满的  则满的进行等待
                    nanos = fullWaitSet.awaitNanos(nanos);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            log.debug("加入任务队列");
            queue.addLast(element);
            // 添加成功之后唤醒 条件为空的等待
            emptyWaitSet.signal();
        } finally {
            lock.unlock();
        }
        return true;
    }

    public T poll(Long timeout, TimeUnit timeUnit) {
        lock.lock();
        try {
            // 将timeOut 统一转换成纳秒
            long nanos = timeUnit.toNanos(timeout);
            while (queue.isEmpty()) {
                try {
                    if (nanos <= 0) {
                        return null;
                    }
                    // 返回的是剩余时间
                    nanos = emptyWaitSet.awaitNanos(nanos);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            T t = queue.removeFirst();
            fullWaitSet.signal();
            return t;
        } finally {
            lock.unlock();
        }
    }

    public int size() {
        lock.lock();
        try {
            return queue.size();
        } finally {
            lock.unlock();
        }
    }

    public void tryPut(RejectPolicy<T> rejectPolicy, T task) {
        lock.lock();
        try {
            if (queue.size() == capcity) {
                rejectPolicy.reject(this, task);
            } else {
                log.debug("加入任务队列{}", task);
                queue.addLast(task);
                emptyWaitSet.signal();
            }
        } finally {
            lock.unlock();
        }
    }
}
